package com.sdkx.wear_os.base

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import com.sdkx.wear_os.customview.customizeDialogCenter
import com.gyf.immersionbar.ImmersionBar
import com.sdkx.wear_os.R
import com.sdkx.wear_os.utils.SoftKeyBoardListener
import com.sdkx.wear_os.utils.SoftKeyBoardListener.hideSoftKeyboard
import com.sdkx.wear_os.utils.getVmClazz
import com.sdkx.wear_os.utils.launchAndCollectInx
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch


/**
 * Fragment基类
 * SimpleImmersionOwner 沉浸式状态栏
 */
@Suppress("UNCHECKED_CAST", "LeakingThis")
abstract class BaseFragment<VM : BaseViewModel, DB : ViewDataBinding> : Fragment() {
    //是否第一次加载
    private var isFirst: Boolean = true

    //加载框
    private var loadDialog: Dialog? = null

    //加载框布局
    private var loadView: View? = null

    //状态栏是否黑色
    var isDarkFont: Boolean = true


    //数据绑定
    lateinit var mDataBinding: DB
    lateinit var mViewModel: VM
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mDataBinding = DataBindingUtil.inflate(inflater, initLayout(), container, false)
        mDataBinding.lifecycleOwner = this
        return mDataBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel = createViewModel()
        //实例化
        initView(savedInstanceState)
        //是否懒加载
        onVisible()
        loadDialog()
        //监听
        initListener()
        setSoftKeyBoardListener()
    }


    override fun onResume() {
        super.onResume()
        hideSoftKeyboard(requireActivity())
        onVisible()
    }

    override fun onPause() {
        super.onPause()
        //隐藏软键盘
        hideSoftKeyboard(requireActivity())
    }

    /**
     * 设置toolbar
     */
    fun initToolbar(
        toolbar: androidx.appcompat.widget.Toolbar?
    ) {
        ImmersionBar.with(this).titleBar(toolbar).statusBarDarkFont(isDarkFont)
            .init()
    }

    fun initImmersionBar() {
        ImmersionBar.with(this).statusBarColorTransformEnable(false)
            .navigationBarColor(R.color.white).statusBarDarkFont(isDarkFont).keyboardEnable(false)
            .init()
    }


    /**
     * 绑定布局
     */
    abstract fun initLayout(): Int

    /**
     * 用于实例化
     */
    abstract fun initView(savedInstanceState: Bundle?)

    /**
     * 用于监听
     */
    open fun initListener() {
    }

    /**
     * 懒加载
     */
    abstract fun lazyLoadData()

    /**
     * 是否需要懒加载
     */
    private fun onVisible() {
        if (lifecycle.currentState == Lifecycle.State.STARTED && isFirst) {
            isFirst = false
            lazyLoadData()
        }
    }

    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(
            this
        )[getVmClazz(this)]
    }

    /**
     * 显示加载框
     */
    @SuppressLint("InflateParams")
    fun showDialog() {
        if (loadView == null) {
            loadView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_progress, null)
            (loadView as View).findViewById<ImageView>(R.id.progress_iv)
                .setImageResource(R.drawable.load_git)
        }
        if (loadDialog == null) {
            loadDialog = customizeDialogCenter(requireActivity(), loadView!!, false)
        }
        loadDialog?.show()
    }

    /**
     * 隐藏加载框
     */
    private fun dismissDialog() {
        loadDialog?.run {
            if (isShowing) {
                dismiss()
                loadView = null
                loadDialog = null
            }
        }
    }

    /**
     * 加载中
     */
    private fun loadDialog() {
        mViewModel.loadingChange.showDialog.launchAndCollectInx(lifecycle, action = {
            if (it)
                showDialog()
            else
                dismissDialog()

        })
    }

    /**
     * 添加软键盘的监听
     */
    private fun setSoftKeyBoardListener() {
        //监听软件盘是否弹起
        SoftKeyBoardListener.setListener(requireActivity(), object :
            SoftKeyBoardListener.OnSoftKeyBoardChangeListener {

            override fun keyBoardShow(height: Int) {
                MainScope().launch {
                    mViewModel.isShowKey.emit(height)
                }
            }

            override fun keyBoardHide(height: Int) {
                MainScope().launch {
                    mViewModel.isShowKey.emit(0)
                }
            }
        })
    }
}

